package com.hualude.roadsign.repository;

import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.OrgDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by xu-jiaHui on 2017/4/12.
 */
public class OrgFatherAndChildRepositoryImpl {
    @PersistenceContext
    private EntityManager em;

    public List<OrgDto> getMainOrgIdAndNameByOrgId(DTRequestDto dtRequestDto, Integer orgId) throws Exception {
        String sql = "select o.OrgId,o.OrgName from tb_org o,tb_org_father_and_child fc where fc.OrgId=" + orgId + " and " +
                "o.OrgId=fc.MainOrgId and o.OrgName like '%" + dtRequestDto.getSearch() + "%' order by o.OrgId desc";
        Query query = em.createNativeQuery(sql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(OrgDto.class));
        List<OrgDto> orgDtos = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return orgDtos;
    }

    public Integer getMainOrgCountByOrgId(DTRequestDto dtRequestDto, Integer orgId) throws Exception {
        String sql = "select count(*) from tb_org o,tb_org_father_and_child fc where fc.OrgId=" + orgId + " and " +
                "o.OrgId=fc.MainOrgId and o.OrgName like '%" + dtRequestDto.getSearch() + "%'";
        Query query = em.createNativeQuery(sql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

}
